﻿using Microsoft.EntityFrameworkCore;
using ZH.GPT.Domains.User.Response;
using ZH.GPT.Extend;
using ZH.GPT.Infrastructures.Entities;
using ZH.GPT.Infrastructures.Enum;
using ZH.GPT.Infrastructures.Extension;
using ZH.GPT.Infrastructures.Repositories.Interface;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Z.EntityFramework.Plus;
using ZH.GPT.Domains.ChatMessage.Response;
using ZH.GPT.Domains.ChatMessage.Request;
using ZH.RetailContainer.CommLibrary;

namespace ZH.GPT.Infrastructures.Repositories
{
    /// <summary>
    /// 消息Repository
    /// </summary>
    public class ChatRepository : BaseRepository, IChatRepository
    {
        /// <summary>
        /// 用户Service构造函数
        /// </summary>
        /// <param name="dbContextFactory"></param>
        public ChatRepository(IDbContextFactory dbContextFactory) : base(dbContextFactory)
        {

        }
        /// <summary>
        /// 添加聊天
        /// </summary>
        /// <param name="chat"></param>
        /// <returns></returns>

        public async Task<bool> AddChat(Chat chat)
        {
            bool isSucc = await base.AddAsync(chat);
            return isSucc;
        }
        /// <summary>
        /// 添加聊天信息
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public async Task<bool> AddChatMessage(ChatMessage msg)
        {
            bool isSucc = await base.AddAsync(msg);
            return isSucc;
        }

        public async Task<bool> AddChatMessages(List<ChatMessage> msgs)
        {
            int count = await base.AddBatchAsync(msgs);
            return count > 0;
        }

        static string desKey = "A1B2C3D4E5F60708";
        /// <summary>
        /// 获取消息
        /// </summary>
        /// <param name="chatMessage"></param>
        /// <returns></returns>
        public async Task<ChatMessagesPDTO> GetChatMessageAsync(ChatMessageQDTO chatMessage)
        {
            dbContext = (MainDBContext)dbContextFactory.GetDbContext(DBOption.Master);
            var queryR = dbContext.ChatMessage.Where(cm => cm.ChatId == chatMessage.SearchCriteria.ChatId);
            if (chatMessage.SearchCriteria.Role != null)
                queryR = queryR.Where(cm => cm.Role == chatMessage.SearchCriteria.Role);
            var query = queryR.Select(m => new ChatMessageDTO
            {
                Id = m.Id,
                UserId = m.UserId,
                ChatId = m.ChatId,
                Content = m.Content,
                //Content = EncryptionAndDecryptionHelper.DecryptDES(m.Content, desKey),
                Sort = m.Sort,
                Role = m.Role,
                CreatedTime = m.CreatedTime,
            }); ;
            int count = await query.CountAsync();
            query = query.OrderByDescending(q => q.Sort);
            query = query
              .Skip(chatMessage.PageSize * (chatMessage.PageIndex - 1))
              .Take(chatMessage.PageSize);
            var result = await query.ToListAsync();

            ChatMessagesPDTO chatMessagesPDTO = new ChatMessagesPDTO();
            chatMessagesPDTO.CurrentPage = chatMessage.PageIndex;
            chatMessagesPDTO.PageSize = chatMessage.PageSize;
            chatMessagesPDTO.TotalCount = count;
            chatMessagesPDTO.RoutingTasks = result;
            chatMessagesPDTO.RoutingTasks = result;

            return chatMessagesPDTO;
        }
        /// <summary>
        /// 获取聊天信息条数
        /// </summary>
        /// <param name="chatId"></param>
        /// <returns></returns>
        public async Task<int> GetChatMessageCount(string chatId)
        {
            dbContext = (MainDBContext)dbContextFactory.GetDbContext(DBOption.Master);
            return await dbContext.ChatMessage.Where(p => p.ChatId == chatId).CountAsync();
        }

        /// <summary>
        /// 新增消息
        /// </summary>
        /// <param name="chatMessage"></param>
        /// <returns></returns>
        public async Task<(bool, string)> AddChatMessageAsync(ChatMessageDTO chatMessage)
        {
            (bool isSucceed, string message) result = (false, "");
            dbContext = (MainDBContext)dbContextFactory.GetDbContext(DBOption.Master);
            dbContext.ChatMessage.Add(new ChatMessage()
            {
                Id = Guid.NewGuid().ToString("N"),
                UserId = chatMessage.UserId,
                ChatId = chatMessage.ChatId,
                Content = chatMessage.Content,
                Sort = Int64.Parse(DateTime.Now.ToString("yyyyMMddHHmmssfff")),
                Role = chatMessage.Role,
                CreatedTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
            });
            int i = await dbContext.SaveChangesAsync();
            if (i > 0)
                result.isSucceed = true;
            else
                result.message = "数据库写入失败，请稍后重试！";
            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<List<ChatPDTO>> GetChatsAsync(string userId)
        {
            dbContext = (MainDBContext)dbContextFactory.GetDbContext(DBOption.Slave);
            var chatpdtos = await dbContext.Chat.Where(p => p.UserId == userId)
                .Select(p => new ChatPDTO
                {
                    Id = p.Id,
                    Description = p.Description,
                    CreatedTime = p.CreatedTime,
                    Role = p.Role,
                    Model = p.Model
                }).ToListAsync();
            return chatpdtos;
        }

        public async Task<User> GetUser(string userId)
        {
            var dbContext = (MainDBContext)dbContextFactory.GetDbContext(DBOption.Slave);
            return await dbContext.Users.FirstOrDefaultAsync(p => p.Id ==  userId);
        }

        public void UpdateUser(User user)
        {
            dbContext.Users.Update(user);
        }
    }
}
